<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

	class FrontView {
		var $data;
		var $page;
		var $admin='';

		function __construct()
		{
			$this->CI = &get_instance();
			$this->CI->load->helper('url');
			$this->CI->load->model('PageModel');
		}
		
		public function view($admin="", $parent="", $slug="")
		{
			if (!empty($admin)) 
				$this->admin = $admin;

			if (!empty($parent))
				$data['parent'] = $parent;
			else
				$data['parent'] = $this->CI->uri->segment(2);;
			

			$data['HeadTags'] = $this->getHeadTags();
			
			$data['video'] = $this->getVideo();
			
			if (!empty($slug))
				$data['slug'] = $slug;
			else
				$data['slug'] = $this->getSlug();

			return $data;
		}

		private function getHeadTags($xml = false, $i = "\t") 
		{
			$result = "\n".
				$this->getMetaTags($xml, $i).
				$this->getStyleTags($xml, $i).
				$this->getJavaTags($i).
				$this->getFaviconTags($xml, $i).
				"\n";
			return $result;
		}
		
		private function &getMetaTags($xml = false, $i = "\t") 
		{
			$url = $this->CI->uri->segment_array();

			if (count($url) > 0) {
				if(!empty($url[1])) $ur = '/'.$url[1].'/';
				if(!empty($url[2]) && ereg("[^0-9]", $url[2])) $ur .= $url[2].'/';
				if(!empty($url[3]) && ereg("[^0-9]", $url[3])) $ur .= $url[3].'/';
			}else{
				$ur = '/';
			}   
			//print_r($ur);
			
			$this->page = $this->CI->PageModel->getPageByLink($ur, false);
			$end = $xml ? ' /' : '';
			$result = "$i<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"$end>\n";
			if(!empty($this->page->robots))
				$result .= "$i<meta name=\"ROBOTS\" content=\"{$this->page->robots}\"$end>\n";
			if(!empty($this->page->keywords))
				$result .= "$i<meta name=\"Keywords\" content=\"{$this->page->keywords}\"$end>\n";
			if(!empty($this->page->description))
				$result .= "$i<meta name=\"Description\" content=\"{$this->page->description}\"$end>\n";

			return $result;
		}
		
		private function &getJavaTags($i = "\t") 
		{
			$array = explode(',', $this->page->js);
			$result = '';
			foreach($array as $js)
				$result .= "$i<script src=\"/res/js/$js\" type=\"text/javascript\"></script>\n";

			return $result;
		}
		
		private function &getStyleTags($xml = false, $i = "\t") 
		{
			$array = explode(',', $this->page->css);
			$result = '';
			$end = $xml ? ' /' : '';

			foreach($array as $sheet)
				$result .= "$i<link href=\"/res/css/$this->admin$sheet\" type=\"text/css\" rel=\"stylesheet\"$end>\n";

			return $result;
		}
		
		private function getFaviconTags($xml = false, $i = "\t") 
		{
			$end = $xml ? ' /' : '';
				
			$result = "$i<link rel=\"icon\" type=\"image/x-icon\" href=\"/res/img/favicon.ico\"$end>\n";
			return $result;
		}
		
		private function getSlug() 
		{
			return $this->page->slug;
		}
		
		private function getVideo() 
		{
			return $this->page->video;
		}
	}